<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { UserItem } from '@/api/user/types'
import { useValidator } from '@/hooks/web/useValidator'
import { saveUserApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useEventBus } from '@/hooks/event/useEventBus'

const { emit } = useEventBus()
const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<UserItem>,
    default: () => undefined
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const validatePass = async (rule: any, value: any, callback: any) => {
  const ruleFormRef: any = await getElFormExpose()
  const formData = await getFormData()
  if (value === '') {
    callback(new Error('密码不能为空！'))
  } else {
    if (formData.pwd !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('againPwd', () => null)
    }
    callback()
  }
}
const validatePass2 = async (rule: any, value: any, callback: any) => {
  const formData = await getFormData()
  if (value === '') {
    callback(new Error('请输入确认密码！'))
  } else if (value !== formData.pwd) {
    callback(new Error('两次密码不一致!'))
  } else {
    callback()
  }
}

const rules: any = reactive({
  username: [required()],
  pwd: [
    { required: true, message: '密码不能为空！' },
    { validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度最少6位！' }
  ],
  againPwd: [
    { required: true, message: '确认密码不能为空！' },
    { validator: validatePass2, trigger: 'blur' },
    { min: 6, message: '密码长度最少6位！' }
  ],
  mobile: [{ max: 11, min: 11, message: '手机号格式不正确！' }]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    saveUserApi(formData)
      .then((res) => {
        console.log(res)
        if (res.code != 200) {
          ElMessage.error(res.message)
        } else {
          ElMessage.success({
            duration: 1000,
            message: res.message,
            onClose: () => {
              emit('getList', 'add')
            }
          })
        }
      })
      .catch((err) => {
        console.log(err)
        ElMessage.error(err)
      })
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // 如果是修改信息则删除密码校验和用户名信息
    let disabled = false
    if (currentRow?.id) {
      rules.pwd = null
      rules.againPwd = null
      disabled = true
    } else {
      rules.pwd = [
        { required: true, message: '密码不能为空！' },
        { validator: validatePass, trigger: 'blur' },
        { min: 6, message: '密码长度最少6位！' }
      ]
      rules.againPwd = [
        { required: true, message: '确认密码不能为空！' },
        { validator: validatePass2, trigger: 'blur' },
        { min: 6, message: '密码长度最少6位！' }
      ]
    }
    setSchema([
      {
        field: 'username',
        path: 'componentProps.disabled',
        value: disabled
      }
    ])
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
